package SortExe;

import java.util.Arrays;

public class InsetSort {

    public static void insertSort1(int[] arr){
        if (arr ==null || arr.length <2){
            return;
        }
        for (int i = 1; i < arr.length; i++) {
            for (int j = i-1; j >=0 ; j--) {
                boolean flg = false;
                if (arr[j] > arr[j+1]){
                    swap(arr,j,j+1);
                    flg = true;
                }
                if (flg == false){
                    break;//是否有必要这么优化
                }
            }

        }
    }

    public static void insertSort2(int[] arr){
        if (arr==null || arr.length <2){
            return;
        }
        for (int i = 1; i < arr.length; i++) {
            for (int j = i-1; j >= 0 && arr[j]>=arr[j+1] ; j--) {
                swap(arr,j,j+1);
            }

        }
    }


    public static void swap(int[] arr,int x,int y){
        int tmp = arr[x];
        arr[x] = arr[y];
        arr[y] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {1,5,4,2,4,6,7,11};
        insertSort2(arr);
        System.out.println(Arrays.toString(arr));
    }
}
